package org.example.controller;

import org.example.controller.pojo.MenuItem;
import org.example.dao.pojo.Account;
import org.example.service.AccountService;
import org.example.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/demo")
public class DemoController {

    @RequestMapping(value = "handle01")
    public String handle01() {
        return "Hey handle01";
    }

    @RequestMapping("upload_form")
    public ModelAndView showUploadForm() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("upload_form");
        return modelAndView;
    }

    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public String upload(MultipartFile uploadFile, HttpServletRequest request) throws IOException {
        // ⽂件原名，如xxx.jpg
        String originalFilename = uploadFile.getOriginalFilename();
        // 获取⽂件的扩展名,如jpg
        String extendName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
        String uuid = UUID.randomUUID().toString();
        // 新的⽂件名字
        String newName = uuid + "." + extendName;
        String realPath = request.getSession().getServletContext().getRealPath("/uploads");
        // 解决⽂件夹存放⽂件数量限制，按⽇期存放
        String datePath = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        File folder = new File(realPath + "/" + datePath);
        if(!folder.exists()) {
            folder.mkdirs();
        }

        uploadFile.transferTo(new File(folder,newName));
        return "success";
    }

    @Autowired
    private AccountService accountService;

    @RequestMapping(value = "accounts", method = RequestMethod.GET)
    public @ResponseBody List<Account> getAccounts() throws Exception {
        return accountService.queryAccountList();
    }

    @Autowired
    private MenuService menuService;

    @RequestMapping(value = "menus", method = RequestMethod.GET)
    public @ResponseBody List<MenuItem> getMenuItems() {
        return menuService.buildMenu();
    }
}
